import { Component, Input, OnInit } from '@angular/core';

@Component({
    selector: 'app-show-json',
    templateUrl: './json.component.html',
    styleUrls: ['./json.component.less']
})
export class ShowJsonComponent implements OnInit {
    @Input()
    json: any;

    // 需要展示的json对象
    content!: string;

    ngOnInit(): void {
        this.content = this.jsonShowFn(this.json);
    }

    jsonShowFn(json: any): string {
        if (typeof json !== 'string') {
            json = JSON.stringify(json, function (this: any, key: string, value: any) {}, 2);
        }

        json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
        return json.replace(
            /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
            (match: string) => {
                let cls = 'color: darkorange;';
                if (/^"/.test(match)) {
                    if (/:$/.test(match)) {
                        cls = 'color: red;';
                    } else {
                        cls = 'color: green;';
                    }
                } else if (/true|false/.test(match)) {
                    cls = 'color: blue;';
                } else if (/null/.test(match)) {
                    cls = 'color: magenta;';
                }
                return `<span style="${cls}">${match}</span>`;
            }
        );
    }
}
